<!DOCTYPE html>
<html lang="zh-CN">
  <head>
  <meta charset="UTF-8">
  <meta 
    name="viewport"
    content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
  <meta 
    http-equiv="X-UA-Compatible" 
    content="ie=edge">
  <meta 
    name="theme-color" 
    content="#fff" 
    id="theme-color">
  <meta 
    name="description" 
    content="hexoDemo用于介绍如何使用hexo">
  <link 
    rel="icon" 
    href="/">
  <title>02-Ajax入门和发送http请求</title>
  
    
      <meta 
        property="og:title" 
        content="02-Ajax入门和发送http请求">
    
    
      <meta 
        property="og:url" 
        content="https://zwl5670.gitee.io/2006/06/01/06-JavaScript%E5%9F%BA%E7%A1%80%EF%BC%9A%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B/02-Ajax%E5%85%A5%E9%97%A8%E5%92%8C%E5%8F%91%E9%80%81http%E8%AF%B7%E6%B1%82/index.html">
    
    
      <meta 
        property="og:img" 
        content="https://img.songhn.com/img/Y67gdd.png">
    
    
      <meta 
        property="og:img" 
        content="hexoDemo用于介绍如何使用hexo">
    
    
      <meta 
        property="og:type" 
        content="article">
      <meta 
        property="og:article:published_time" 
        content="2006-06-01">
      <meta 
        property="og:article:modified_time" 
        content="2023-03-14">
      <meta 
        property="og:article:author" 
        content="zwl5670">
      
        
          <meta 
            property="og:article:tag" 
            content="JS基础异步">
        
      
    
  
  
  <link rel="preload" href="//at.alicdn.com/t/font_1946621_i1kgafibvw.css" as="style" >
  <link rel="preload" href="//at.alicdn.com/t/font_1952792_89b4ac4k4up.css" as="style" >
  <link rel="preload" href="/css/main.css" as="style" >
  
  <link rel="modulepreload" href="//instant.page/5.1.0">
  
  <link rel="stylesheet" href="/css/main.css">
  
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1946621_i1kgafibvw.css">
  
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1952792_89b4ac4k4up.css">
  
  
  
    <link rel="stylesheet" href="/js/lib/lightbox/baguetteBox.min.css">
  
  <script>
    function loadScript(url, cb) {
      var script = document.createElement('script');
      script.src = url;
      if (cb) script.onload = cb;
      script.async = true;
      document.body.appendChild(script);
    }
    function loadCSS(href, data, attr) {
      var sheet = document.createElement('link');
      sheet.ref = 'stylesheet';
      sheet.href = href;
      sheet.dataset[data] = attr;
      document.head.appendChild(sheet);
    }
    function changeCSS(cssFile, data, attr) {
      var oldlink = document.querySelector(data);
      var newlink = document.createElement("link");
      newlink.setAttribute("rel", "stylesheet");
      newlink.setAttribute("href", cssFile);
      newlink.dataset.prism = attr;
      document.head.replaceChild(newlink, oldlink);
    }
  </script>
  
    
  
  <script>
    // control reverse button
    var reverseDarkList = {
      dark: 'light',
      light: 'dark'
    };
    var themeColor = {
      dark: '#1c1c1e',
      light: '#fff'
    }
    // get the data of css prefers-color-scheme
    var getCssMediaQuery = function() {
      return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    };
    // reverse current darkmode setting function
    var reverseDarkModeSetting = function() {
      var setting = localStorage.getItem('user-color-scheme');
      if(reverseDarkList[setting]) {
        setting = reverseDarkList[setting];
      } else if(setting === null) {
        setting = reverseDarkList[getCssMediaQuery()];
      } else {
        return;
      }
      localStorage.setItem('user-color-scheme', setting);
      return setting;
    };
    // apply current darkmode setting
  </script>
  
    <script>
      var setDarkmode = function(mode) {
      var setting = mode || localStorage.getItem('user-color-scheme');
      if(setting === getCssMediaQuery()) {
        document.documentElement.removeAttribute('data-user-color-scheme');
        localStorage.removeItem('user-color-scheme');
        document.getElementById('theme-color').content = themeColor[setting];
        document.getElementById('theme-color').dataset.mode = setting;
      } else if(reverseDarkList[setting]) {
        document.documentElement.setAttribute('data-user-color-scheme', setting);
        document.getElementById('theme-color').content = themeColor[setting];
        document.getElementById('theme-color').dataset.mode = setting;
      } else {
        document.documentElement.removeAttribute('data-user-color-scheme');
        localStorage.removeItem('user-color-scheme');
        document.getElementById('theme-color').content = themeColor[getCssMediaQuery()];
        document.getElementById('theme-color').dataset.mode = getCssMediaQuery();
      }
    };
    setDarkmode();
    </script>
  
  
  
    <link rel="preload" href="/js/lib/lightbox/baguetteBox.min.js" as="script">
    <link rel="preload" href="/js/lib/lightbox/baguetteBox.min.css" as="style" >
  
  
    <link rel="preload" href="/js/lib/lozad.min.js" as="script">
  
  
  
  
  
  
<meta name="generator" content="Hexo 6.3.0"></head>

  <body>
    <div class="wrapper">
       
      <nav class="navbar">
  <div class="navbar-logo">
    <a class="navbar-logo-main" href="/">
      
      <span class="navbar-logo-dsc">前端面试</span>
      </a>
  </div>
  <div class="navbar-menu">
    
      <a 
        href="/" 
        class="navbar-menu-item">
        
          首页
        
      </a>
    
      <a 
        href="/archives" 
        class="navbar-menu-item">
        
          归档
        
      </a>
    
      <a 
        href="/tags" 
        class="navbar-menu-item">
        
          标签
        
      </a>
    
      <a 
        href="/categories" 
        class="navbar-menu-item">
        
          分类
        
      </a>
    
      <a 
        href="/about" 
        class="navbar-menu-item">
        
          关于
        
      </a>
    
      <a 
        href="/links" 
        class="navbar-menu-item">
        
          友链
        
      </a>
    
    <button 
      class="navbar-menu-item darknavbar navbar-menu-btn" 
      aria-label="Toggle dark mode"
      id="dark">
      <i class="iconfont icon-weather"></i>
    </button>
    <button 
      class="navbar-menu-item searchnavbar navbar-menu-btn" 
      aria-label="Toggle search"
      id="search">
      <!-- <i 
        class="iconfont icon-search" 
        style="font-size: 1.2rem; font-weight: 400;">
      </i> -->
      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img"
        class="iconify iconify--ion" width="28" height="28" preserveAspectRatio="xMidYMid meet" viewBox="0 0 512 512">
        <path fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="28"
          d="M256 80a176 176 0 1 0 176 176A176 176 0 0 0 256 80Z"></path>
        <path fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="28"
          d="M232 160a72 72 0 1 0 72 72a72 72 0 0 0-72-72Z"></path>
        <path fill="none" stroke="currentColor" stroke-linecap="round" stroke-miterlimit="10" stroke-width="28"
          d="M283.64 283.64L336 336"></path>
      </svg>
    </button>
  </div>
</nav> 
      
      <div 
        id="local-search" 
        style="display: none">
        <input
          class="navbar-menu-item"
          id="search-input"
          placeholder="请输入搜索内容..." />
        <div id="search-content"></div>
      </div>
      
      <div class="section-wrap">
        <div class="container">
          <div class="columns">
            <aside class="left-column">
              
              <div class="card card-author">
                
  <img 
    src="https://img.songhn.com/img/Y67gdd.png" 
    class="author-img"
    width="88"
    height="88"
    alt="author avatar">

<p class="author-name">zwl5670</p>
<p class="author-description">前端学习资料</p>
<div class="author-message">
  <a 
    class="author-posts-count" 
    href="/archives">
    <span>215</span>
    <span>文章</span>
  </a>
  <a 
    class="author-categories-count" 
    href="/categories">
    <span>14</span>
    <span>分类</span>
  </a>
  <a 
    class="author-tags-count" 
    href="/tags">
    <span>14</span>
    <span>标签</span>
  </a>
</div>

              </div>
               <div class="sticky-tablet">
  
  
    <article class="display-when-two-columns spacer">
      <div class="card card-content toc-card">
        <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%90%8C%E6%AD%A5%E5%92%8C%E5%BC%82%E6%AD%A5%E5%9B%9E%E9%A1%BE"><span class="toc-text">同步和异步回顾</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%90%8C%E6%AD%A5%E5%92%8C%E5%BC%82%E6%AD%A5%E7%9A%84%E7%AE%80%E5%8D%95%E7%90%86%E8%A7%A3"><span class="toc-text">同步和异步的简单理解</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%82%E6%AD%A5%E6%9B%B4%E6%96%B0%E7%BD%91%E7%AB%99"><span class="toc-text">异步更新网站</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Ajax"><span class="toc-text">Ajax</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Ajax-%E7%9A%84%E6%A6%82%E5%BF%B5"><span class="toc-text">Ajax 的概念</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Ajax-%E5%8E%9F%E7%90%86%EF%BC%88%E5%8F%91%E9%80%81-Ajax-%E8%AF%B7%E6%B1%82%E7%9A%84%E4%BA%94%E4%B8%AA%E6%AD%A5%E9%AA%A4%EF%BC%89"><span class="toc-text">Ajax 原理（发送 Ajax 请求的五个步骤）</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#XMLHttpRequest-%E5%AF%B9%E8%B1%A1%E8%AF%A6%E8%A7%A3"><span class="toc-text">XMLHttpRequest 对象详解</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%91%E9%80%81%E8%AF%B7%E6%B1%82"><span class="toc-text">发送请求</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#POST-%E8%AF%B7%E6%B1%82%E6%97%B6%E6%B3%A8%E6%84%8F"><span class="toc-text">POST 请求时注意</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#onreadystatechange-%E4%BA%8B%E4%BB%B6"><span class="toc-text">onreadystatechange 事件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9C%8D%E5%8A%A1%E5%99%A8%E5%93%8D%E5%BA%94%E7%9A%84%E5%86%85%E5%AE%B9"><span class="toc-text">服务器响应的内容</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%89%8B%E5%86%99-Ajax"><span class="toc-text">手写 Ajax</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%89%8B%E5%86%99%E7%AC%AC%E4%B8%80%E4%B8%AA-Ajax-%E8%AF%B7%E6%B1%82"><span class="toc-text">手写第一个 Ajax 请求</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B0%81%E8%A3%85-Ajax-%E8%AF%B7%E6%B1%82%EF%BC%88%E9%87%8D%E8%A6%81%EF%BC%89"><span class="toc-text">封装 Ajax 请求（重要）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Ajax-%E8%AF%B7%E6%B1%82%EF%BC%9Aget-%E8%AF%B7%E6%B1%82%E4%B8%BE%E4%BE%8B"><span class="toc-text">Ajax 请求：get 请求举例</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Ajax-%E5%A4%9A%E4%B8%AA%E6%8E%A5%E5%8F%A3%E7%9A%84%E5%B5%8C%E5%A5%97%E8%AF%B7%E6%B1%82"><span class="toc-text">Ajax 多个接口的嵌套请求</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#jQuery-%E4%B8%AD%E7%9A%84-Ajax"><span class="toc-text">jQuery 中的 Ajax</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%88%91%E7%9A%84%E5%85%AC%E4%BC%97%E5%8F%B7"><span class="toc-text">我的公众号</span></a></li></ol>
      </div>
    </article>
  
  
  <article class="card card-content categories-widget">
    <div class="categories-card">
  <div class="categories-header">
    <i 
      class="iconfont icon-fenlei" 
      style="padding-right: 2px;">
    </i>分类
  </div>
  <div class="categories-list">
    
      <a href="/categories/%E5%89%8D%E7%AB%AF%E5%B7%A5%E5%85%B7/">
        <div class="categories-list-item">
          前端工具
          <span class="categories-list-item-badge">13</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          CSS基础
          <span class="categories-list-item-badge">18</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E8%BF%9B%E9%98%B6/">
        <div class="categories-list-item">
          CSS进阶
          <span class="categories-list-item-badge">9</span>
        </div>
      </a>
    
      <a href="/categories/HTML/">
        <div class="categories-list-item">
          HTML
          <span class="categories-list-item-badge">12</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          JS基础
          <span class="categories-list-item-badge">56</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80ES6/">
        <div class="categories-list-item">
          JS基础ES6
          <span class="categories-list-item-badge">10</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80%E5%BC%82%E6%AD%A5/">
        <div class="categories-list-item">
          JS基础异步
          <span class="categories-list-item-badge">11</span>
        </div>
      </a>
    
      <a href="/categories/JS%E8%BF%9B%E9%98%B6/">
        <div class="categories-list-item">
          JS进阶
          <span class="categories-list-item-badge">11</span>
        </div>
      </a>
    
      <a href="/categories/%E7%A7%BB%E5%8A%A8web/">
        <div class="categories-list-item">
          移动web
          <span class="categories-list-item-badge">3</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E5%92%8CDOM/">
        <div class="categories-list-item">
          CSS和DOM
          <span class="categories-list-item-badge">6</span>
        </div>
      </a>
    
      <a href="/categories/Node/">
        <div class="categories-list-item">
          Node
          <span class="categories-list-item-badge">16</span>
        </div>
      </a>
    
      <a href="/categories/Vue%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          Vue基础
          <span class="categories-list-item-badge">15</span>
        </div>
      </a>
    
      <a href="/categories/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/">
        <div class="categories-list-item">
          性能优化
          <span class="categories-list-item-badge">7</span>
        </div>
      </a>
    
      <a href="/categories/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%8C%96/">
        <div class="categories-list-item">
          前端工程化
          <span class="categories-list-item-badge">8</span>
        </div>
      </a>
    
  </div>
</div>
  </article>
  
  <article class="card card-content tags-widget">
    <div class="tags-card">
  <div class="tags-header">
    <i 
      class="iconfont icon-biaoqian" 
      style="padding-right: 2px;">
    </i>热门标签
  </div>
  <div class="tags-list">
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80/" 
        title="JS基础">
        <div class="tags-list-item">JS基础</div>
      </a>
    
      <a 
        href="/tags/CSS%E5%9F%BA%E7%A1%80/" 
        title="CSS基础">
        <div class="tags-list-item">CSS基础</div>
      </a>
    
      <a 
        href="/tags/Node/" 
        title="Node">
        <div class="tags-list-item">Node</div>
      </a>
    
      <a 
        href="/tags/Vue%E5%9F%BA%E7%A1%80/" 
        title="Vue基础">
        <div class="tags-list-item">Vue基础</div>
      </a>
    
      <a 
        href="/tags/%E5%89%8D%E7%AB%AF%E5%B7%A5%E5%85%B7/" 
        title="前端工具">
        <div class="tags-list-item">前端工具</div>
      </a>
    
      <a 
        href="/tags/HTML/" 
        title="HTML">
        <div class="tags-list-item">HTML</div>
      </a>
    
      <a 
        href="/tags/JS%E8%BF%9B%E9%98%B6/" 
        title="JS进阶">
        <div class="tags-list-item">JS进阶</div>
      </a>
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80%E5%BC%82%E6%AD%A5/" 
        title="JS基础异步">
        <div class="tags-list-item">JS基础异步</div>
      </a>
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80ES6/" 
        title="JS基础ES6">
        <div class="tags-list-item">JS基础ES6</div>
      </a>
    
      <a 
        href="/tags/CSS%E8%BF%9B%E9%98%B6/" 
        title="CSS进阶">
        <div class="tags-list-item">CSS进阶</div>
      </a>
    
      <a 
        href="/tags/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%8C%96/" 
        title="前端工程化">
        <div class="tags-list-item">前端工程化</div>
      </a>
    
      <a 
        href="/tags/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" 
        title="性能优化">
        <div class="tags-list-item">性能优化</div>
      </a>
    
      <a 
        href="/tags/CSS%E5%92%8CDOM/" 
        title="CSS和DOM">
        <div class="tags-list-item">CSS和DOM</div>
      </a>
    
      <a 
        href="/tags/%E7%A7%BB%E5%8A%A8web/" 
        title="移动web">
        <div class="tags-list-item">移动web</div>
      </a>
    
  </div>
</div>
  </article>
  
  
</div>
            </aside>
            <main class="main-column">
              
<article class="card card-content">
  <header>
    <h1 class="post-title">
      02-Ajax入门和发送http请求
    </h1>
  </header>
  <div class="post-meta post-show-meta">
    <time datetime="2006-05-31T16:00:00.000Z">
      <i 
        class="iconfont icon-calendar" 
        style="margin-right: 2px;">
      </i>
      <span>2006-06-01</span>
    </time>
    
      <span class="dot"></span>
      
        <a 
          href="/categories/JS%E5%9F%BA%E7%A1%80%E5%BC%82%E6%AD%A5/" 
          class="post-meta-link">
          JS基础异步
        </a>
      
    
    
      <span class="dot"></span>
      <span>2.6k 字</span>
    
  </div>
  
    <div 
      class="post-meta post-show-meta" 
      style="margin-top: -10px;">
      <div style="display: flex; align-items: center;">
        <i 
          class="iconfont icon-biaoqian" 
          style="margin-right: 2px; font-size: 1.15rem;">
        </i>
        
          
          <a 
            href="/tags/JS%E5%9F%BA%E7%A1%80%E5%BC%82%E6%AD%A5/" 
            class="post-meta-link">
            JS基础异步
          </a>
        
      </div>
    </div>
  
  </header>
  <div 
    id="section" 
    class="post-content">
    <p><ArticleTopAd></ArticleTopAd></p>
<h2 id="同步和异步回顾"><a href="#同步和异步回顾" class="headerlink" title="同步和异步回顾"></a>同步和异步回顾</h2><h3 id="同步和异步的简单理解"><a href="#同步和异步的简单理解" class="headerlink" title="同步和异步的简单理解"></a>同步和异步的简单理解</h3><ul>
<li><p>同步：必须等待前面的任务完成，才能继续后面的任务。</p>
</li>
<li><p>异步：不受当前任务的影响。</p>
</li>
</ul>
<p>拿排队举例：</p>
<ul>
<li><p>同步：在银行排队时，只有等到你了，才能够去处理业务。</p>
</li>
<li><p>异步：在排队的时候，可以玩手机。</p>
</li>
</ul>
<h3 id="异步更新网站"><a href="#异步更新网站" class="headerlink" title="异步更新网站"></a>异步更新网站</h3><p>我们在访问一个普通的网站时，当浏览器加载完<code>HTML、CSS、JS</code>以后，网站的内容就固定了。如果想让网站内容发生更改，就必须<strong>刷新</strong>页面才能够看到更新的内容。</p>
<p>可如果用到<strong>异步更新</strong>，情况就大为改观了。比如，我们在访问新浪微博时，看到一大半了，点击底部的<strong>加载更多</strong>，会自动帮我们加载更多的微博，同时页面并不会整体刷新。</p>
<p>试想一下，如果没有异步刷新的话，每次点击“加载更多”，网页都要重新刷新，体验就太糟糕了。</p>
<p>web 前端里的异步更新，就要用到 Ajax。很多人说，如果没有 Ajax，就没有互联网的今天。</p>
<p>关于同步和异步的更详细介绍，可以参考本项目的另外一篇文章：《05-JavaScript 基础：异步编程和 Ajax&#x2F;01-单线程和异步》</p>
<h2 id="Ajax"><a href="#Ajax" class="headerlink" title="Ajax"></a>Ajax</h2><h3 id="Ajax-的概念"><a href="#Ajax-的概念" class="headerlink" title="Ajax 的概念"></a>Ajax 的概念</h3><p>在浏览器中，我们可以在不刷新页面的情况下，通过 Ajax 的方式去获取一些新的内容。</p>
<p>Ajax：Asynchronous Javascript And XML（异步 JavaScript 和 XML）。它并不是凭空出现的新技术，而是对于现有技术的结合。Ajax 的核心是 js 对象：<strong>XMLHttpRequest</strong>。</p>
<h3 id="Ajax-原理（发送-Ajax-请求的五个步骤）"><a href="#Ajax-原理（发送-Ajax-请求的五个步骤）" class="headerlink" title="Ajax 原理（发送 Ajax 请求的五个步骤）"></a>Ajax 原理（发送 Ajax 请求的五个步骤）</h3><blockquote>
<p>其实也就是 使用 XMLHttpRequest 对象的五个步骤。</p>
</blockquote>
<p>我们先回忆一下，一个完整的 HTTP 请求需要的是：</p>
<ul>
<li><p>请求的网址、请求方法 get&#x2F;post。</p>
</li>
<li><p>提交请求的内容数据、请求主体等。</p>
</li>
<li><p>接收响应回来的内容。</p>
</li>
</ul>
<p>发送 Ajax 请求的五个步骤：</p>
<p>（1）创建异步对象，即 XMLHttpRequest 对象。</p>
<p>（2）使用 open 方法设置请求参数。<code>open(method, url, async)</code>。参数解释：请求的方法、请求的 url、是否异步。第三个参数如果不写，则默认为 true。</p>
<p>（3）发送请求：<code>send()</code>。</p>
<p>（4）注册事件：注册 onreadystatechange 事件，状态改变时就会调用。</p>
<p>如果要在数据完整请求回来的时候才调用，我们需要手动写一些判断的逻辑。</p>
<p>（5）服务端响应，获取返回的数据。</p>
<h2 id="XMLHttpRequest-对象详解"><a href="#XMLHttpRequest-对象详解" class="headerlink" title="XMLHttpRequest 对象详解"></a>XMLHttpRequest 对象详解</h2><p>我们在上一段讲解了使用 XMLHttpRequest 对象的五个步骤。本段，我们讲一下注意事项。</p>
<h3 id="发送请求"><a href="#发送请求" class="headerlink" title="发送请求"></a>发送请求</h3><p>发送请求的方法：</p>
<pre class="highlight"><span class="line"><span class="title function_">open</span>(method, url, <span class="keyword">async</span>);</span><br></pre>

<p>参数解释：</p>
<ul>
<li><p>method：请求的类型；GET 或 POST</p>
</li>
<li><p>url：文件在服务器上的位置</p>
</li>
<li><p>async：true（异步）或 false（同步）</p>
</li>
</ul>
<p>另外还有个方法：（仅用于 POST 请求）</p>
<pre class="highlight"><span class="line"><span class="title function_">send</span>(string);</span><br></pre>

<h3 id="POST-请求时注意"><a href="#POST-请求时注意" class="headerlink" title="POST 请求时注意"></a>POST 请求时注意</h3><p>如果想让 像 form 表单提交数据那样使用 POST 请求，就需要使用 XMLHttpRequest 对象的 setRequestHeader()方法 来添加 HTTP 头。然后在 send() 方法中添加想要发送的数据：</p>
<pre class="highlight"><span class="line">xmlhttp.<span class="title function_">open</span>(<span class="string">&#x27;POST&#x27;</span>, <span class="string">&#x27;ajax_test.php&#x27;</span>, <span class="literal">true</span>);</span><br><span class="line"></span><br><span class="line">xmlhttp.<span class="title function_">setRequestHeader</span>(<span class="string">&#x27;Content-type&#x27;</span>, <span class="string">&#x27;application/x-www-form-urlencoded&#x27;</span>);</span><br><span class="line"></span><br><span class="line">xmlhttp.<span class="title function_">send</span>(<span class="string">&#x27;name=smyhvae&amp;age=27&#x27;</span>);</span><br></pre>

<h3 id="onreadystatechange-事件"><a href="#onreadystatechange-事件" class="headerlink" title="onreadystatechange 事件"></a>onreadystatechange 事件</h3><p>注册 onreadystatechange 事件后，每当 readyState 属性改变时，就会调用 onreadystatechange 函数。</p>
<p>readyState：（存有 XMLHttpRequest 的状态。从 0 到 4 发生变化）</p>
<ul>
<li><p>0: 请求未初始化</p>
</li>
<li><p>1: 服务器连接已建立</p>
</li>
<li><p>2: 请求已接收</p>
</li>
<li><p>3: 请求处理中</p>
</li>
<li><p>4: 请求已完成，且响应已就绪</p>
</li>
</ul>
<p>status：</p>
<ul>
<li><p>200: “OK”。</p>
</li>
<li><p>404: 未找到页面。</p>
</li>
</ul>
<p>在 onreadystatechange 事件中，<strong>当 readyState 等于 4，且状态码为 200 时，表示响应已就绪</strong>。</p>
<h3 id="服务器响应的内容"><a href="#服务器响应的内容" class="headerlink" title="服务器响应的内容"></a>服务器响应的内容</h3><ul>
<li><p>responseText：获得字符串形式的响应数据。</p>
</li>
<li><p>responseXML：获得 XML 形式的响应数据。</p>
</li>
</ul>
<p>如果响应的是普通字符串，就使用 responseText；如果响应的是 XML，使用 responseXML。</p>
<h2 id="手写-Ajax"><a href="#手写-Ajax" class="headerlink" title="手写 Ajax"></a>手写 Ajax</h2><h3 id="手写第一个-Ajax-请求"><a href="#手写第一个-Ajax-请求" class="headerlink" title="手写第一个 Ajax 请求"></a>手写第一个 Ajax 请求</h3><p>get 请求：</p>
<pre class="highlight"><span class="line"><span class="comment">//【发送ajax请求需要五步】</span></span><br><span class="line"><span class="comment">//（1）创建XMLHttpRequest对象</span></span><br><span class="line"><span class="keyword">var</span> xmlhttp = <span class="keyword">new</span> <span class="title class_">XMLHttpRequest</span>();</span><br><span class="line"></span><br><span class="line"><span class="comment">//（2）设置请求的参数。包括：请求的方法、请求的url。</span></span><br><span class="line">xmlhttp.<span class="title function_">open</span>(<span class="string">&#x27;get&#x27;</span>, <span class="string">&#x27;02-ajax.php&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//（3）发送请求</span></span><br><span class="line">xmlhttp.<span class="title function_">send</span>();</span><br><span class="line"></span><br><span class="line"><span class="comment">//（4）注册事件。 onreadystatechange事件，状态改变时就会调用。</span></span><br><span class="line"><span class="comment">//如果要在数据完整请求回来的时候才调用，我们需要手动写一些判断的逻辑。</span></span><br><span class="line">xmlhttp.<span class="property">onreadystatechange</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="comment">// 为了保证 数据 完整返回，我们一般会判断 两个值</span></span><br><span class="line">    <span class="keyword">if</span> (xmlhttp.<span class="property">readyState</span> == <span class="number">4</span> &amp;&amp; xmlhttp.<span class="property">status</span> == <span class="number">200</span>) &#123;</span><br><span class="line">        <span class="comment">//（5）服务端相应：如果能够进入这个判断，说明数据请求成功了</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;数据返回成功：&#x27;</span> + <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(xmlhttp.<span class="property">responseText</span>));</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 伪代码：按业务需要，将接口返回的内容显示在页面上</span></span><br><span class="line">        <span class="comment">// document.querySelector(&#x27;h1&#x27;).innerHTML = xmlhttp.responseText;</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre>

<p>post 请求：</p>
<pre class="highlight"><span class="line"><span class="comment">//（1）异步对象</span></span><br><span class="line"><span class="keyword">var</span> xmlhttp = <span class="keyword">new</span> <span class="title class_">XMLHttpRequest</span>();</span><br><span class="line"></span><br><span class="line"><span class="comment">//（2）设置请求参数。包括：请求的方法、请求的url。</span></span><br><span class="line">xmlhttp.<span class="title function_">open</span>(<span class="string">&#x27;post&#x27;</span>, <span class="string">&#x27;02.post.php&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 如果想要使用post提交数据,必须添加此行</span></span><br><span class="line">xmlhttp.<span class="title function_">setRequestHeader</span>(<span class="string">&#x27;Content-type&#x27;</span>, <span class="string">&#x27;application/x-www-form-urlencoded&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//（3）发送请求</span></span><br><span class="line">xmlhttp.<span class="title function_">send</span>(<span class="string">&#x27;name=fox&amp;age=18&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//（4）注册事件</span></span><br><span class="line">xmlhttp.<span class="property">onreadystatechange</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="comment">//（5）服务端相应</span></span><br><span class="line">    <span class="keyword">if</span> (xmlhttp.<span class="property">readyState</span> == <span class="number">4</span> &amp;&amp; xmlhttp.<span class="property">status</span> == <span class="number">200</span>) &#123;</span><br><span class="line">        <span class="title function_">alert</span>(xmlhttp.<span class="property">responseText</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre>

<h3 id="封装-Ajax-请求（重要）"><a href="#封装-Ajax-请求（重要）" class="headerlink" title="封装 Ajax 请求（重要）"></a>封装 Ajax 请求（重要）</h3><p>上面的代码，执行顺序很好理解，但在实战开发中，是不会这么写的。假如你的页面中，需要调十次接口，那岂不是要手写十遍 Ajax 请求？这样会导致大量的重复代码。</p>
<p>所以，我们需要把重复代码封装成一个公共函数，然后通过<strong>回调函数</strong>处理成功和失败的逻辑。</p>
<p>封装 Ajax 请求的代码如下：(get 请求为例)</p>
<pre class="highlight"><span class="line"><span class="comment">// 封装 Ajax为公共函数：传入回调函数 success 和 fail</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">myAjax</span>(<span class="params">url, success, fail</span>) &#123;</span><br><span class="line">    <span class="comment">// 1、创建XMLHttpRequest对象</span></span><br><span class="line">    <span class="keyword">var</span> xmlhttp;</span><br><span class="line">    <span class="keyword">if</span> (<span class="variable language_">window</span>.<span class="property">XMLHttpRequest</span>) &#123;</span><br><span class="line">        xmlhttp = <span class="keyword">new</span> <span class="title class_">XMLHttpRequest</span>();</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// 兼容IE5、IE6浏览器。不写也没关系</span></span><br><span class="line">        xmlhttp = <span class="keyword">new</span> <span class="title class_">ActiveXObject</span>(<span class="string">&#x27;Microsoft.XMLHTTP&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 2、发送请求</span></span><br><span class="line">    xmlhttp.<span class="title function_">open</span>(<span class="string">&#x27;GET&#x27;</span>, url, <span class="literal">true</span>);</span><br><span class="line">    xmlhttp.<span class="title function_">send</span>();</span><br><span class="line">    <span class="comment">// 3、服务端响应</span></span><br><span class="line">    xmlhttp.<span class="property">onreadystatechange</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (xmlhttp.<span class="property">readyState</span> === <span class="number">4</span> &amp;&amp; xmlhttp.<span class="property">status</span> === <span class="number">200</span>) &#123;</span><br><span class="line">            <span class="keyword">var</span> obj = <span class="title class_">JSON</span>.<span class="title function_">parse</span>(xmlhttp.<span class="property">responseText</span>);</span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;数据返回成功：&#x27;</span> + obj);</span><br><span class="line">            success &amp;&amp; <span class="title function_">success</span>(xmlhttp.<span class="property">responseText</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// 这里的 &amp;&amp; 符号，意思是：如果传了 fail 参数，就调用后面的 fail()；如果没传 fail 参数，就不调用后面的内容。因为 fail 参数不一定会传。</span></span><br><span class="line">            fail &amp;&amp; <span class="title function_">fail</span>(<span class="keyword">new</span> <span class="title class_">Error</span>(<span class="string">&#x27;接口请求失败&#x27;</span>));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 单次调用 ajax</span></span><br><span class="line"><span class="title function_">myAjax</span>(<span class="string">&#x27;a.json&#x27;</span>, <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 多次调用 ajax。接口请求顺序：a --&gt; b --&gt; c</span></span><br><span class="line"><span class="title function_">myAjax</span>(<span class="string">&#x27;a.json&#x27;</span>, <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">    <span class="title function_">myAjax</span>(<span class="string">&#x27;b.json&#x27;</span>, <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">        <span class="title function_">myAjax</span>(<span class="string">&#x27;c.json&#x27;</span>, <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;);</span><br></pre>

<p>学会了封装 get 请求之后，封装 post请求也是类似的写法。</p>
<h3 id="Ajax-请求：get-请求举例"><a href="#Ajax-请求：get-请求举例" class="headerlink" title="Ajax 请求：get 请求举例"></a>Ajax 请求：get 请求举例</h3><p>（1）index.html：</p>
<pre class="highlight"><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">h1</span>&gt;</span>Ajax 发送 get 请求<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;button&quot;</span> <span class="attr">value</span>=<span class="string">&quot;发送get_ajax请求&quot;</span> <span class="attr">id</span>=<span class="string">&quot;btnAjax&quot;</span> /&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">&quot;text/javascript&quot;</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">            <span class="comment">// 绑定点击事件</span></span></span><br><span class="line"><span class="language-javascript">            <span class="variable language_">document</span>.<span class="title function_">querySelector</span>(<span class="string">&#x27;#btnAjax&#x27;</span>).<span class="property">onclick</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span></span><br><span class="line"><span class="language-javascript">                <span class="comment">// 这里直接使用上面封装的 myAjax() 方法即可</span></span></span><br><span class="line"><span class="language-javascript">                <span class="title function_">myAjax</span>(<span class="string">&#x27;02-ajax.php&#x27;</span>, <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span></span><br><span class="line"><span class="language-javascript">                    <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span></span><br><span class="line"><span class="language-javascript">                    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;数据返回成功&#x27;</span>);</span></span><br><span class="line"><span class="language-javascript">                    <span class="comment">// 显示在页面上</span></span></span><br><span class="line"><span class="language-javascript">                    <span class="variable language_">document</span>.<span class="title function_">querySelector</span>(<span class="string">&#x27;h1&#x27;</span>).<span class="property">innerHTML</span> = res;</span></span><br><span class="line"><span class="language-javascript">                    <span class="comment">// alert(xhr.responseText);</span></span></span><br><span class="line"><span class="language-javascript">                &#125;);</span></span><br><span class="line"><span class="language-javascript">            &#125;;</span></span><br><span class="line"><span class="language-javascript">        </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre>

<p>（2）02-ajax.php：</p>
<pre class="highlight"><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line">	<span class="keyword">echo</span> <span class="string">&#x27;smyhvae&#x27;</span>;</span><br><span class="line"> <span class="meta">?&gt;</span></span><br></pre>

<p>效果如下：</p>
<p><img  srcset="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20300%20300'%3E%3C/svg%3E" data-src="http://img.smyhvae.com/20180228_1605.gif" class="lozad post-image"src="http://img.smyhvae.com/20180228_1605.gif"></p>
<h3 id="Ajax-多个接口的嵌套请求"><a href="#Ajax-多个接口的嵌套请求" class="headerlink" title="Ajax 多个接口的嵌套请求"></a>Ajax 多个接口的嵌套请求</h3><p>我们在做异步任务的时候，经常会涉及到多个接口的嵌套请求。比如说，接口 1 请求完成后，需要根据接口 1 的数据请求接口 2；接口 2 请求完成后，需要根据接口 3 的数据请求接口 3，以此类推。</p>
<p>需求描述：</p>
<ul>
<li><p>请求接口 1，根据用户名获取用户 id</p>
</li>
<li><p>请求接口 2，根据用户 id 获取用户的年龄、性别等信息。</p>
</li>
</ul>
<p>代码实现思路：</p>
<pre class="highlight"><span class="line"><span class="title function_">myAjax</span>(<span class="string">&#x27;http://localhost:8888/php/user.php?name=千古&#x27;</span>, <span class="function">(<span class="params">userInfo</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// 根据第一个接口返回的 userInfo.id，继续请求第二个接口</span></span><br><span class="line">    <span class="title function_">myAjax</span>(<span class="string">`http://localhost:8888/php/info.php?id=<span class="subst">$&#123;userInfo[<span class="string">&#x27;id&#x27;</span>]&#125;</span>`</span>, <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(response);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;);</span><br></pre>

<p>我们在实战开发中，经常会涉及到接口请求之间的<strong>依赖</strong>：需要上一个接口请求返回的数据，来发送本次请求。这种场景经常遇到，需要记住。</p>
<p>但这种层层嵌套的代码，会导致<strong>回调地域</strong>的问题，也不利于维护。我们在后续的 ES6 章节中，会讲解 Promise，它是一种更优雅的异步任务解决方案。</p>
<h2 id="jQuery-中的-Ajax"><a href="#jQuery-中的-Ajax" class="headerlink" title="jQuery 中的 Ajax"></a>jQuery 中的 Ajax</h2><p>JQuery 作为最受欢迎的 js 框架之一，常见的 Ajax 已经帮助我们封装好了，只需要调用即可。更为详细的 api 文档可以查阅：<a target="_blank" rel="noopener" href="http://www.w3school.com.cn/jquery/jquery_ref_ajax.asp">w3cSchool_JQueryAjax</a></p>
<p>格式举例：</p>
<pre class="highlight"><span class="line">$.<span class="title function_">ajax</span>(&#123;</span><br><span class="line">    <span class="attr">url</span>: <span class="string">&#x27;https://xxx.com/getUserInfo.php&#x27;</span>, <span class="comment">// 接口的请求地址</span></span><br><span class="line">    <span class="attr">data</span>: <span class="string">&#x27;name=fox&amp;age=18&#x27;</span>, <span class="comment">// 请求参数</span></span><br><span class="line">    <span class="attr">type</span>: <span class="string">&#x27;GET&#x27;</span>, <span class="comment">//请求的方式</span></span><br><span class="line">    <span class="attr">success</span>: <span class="keyword">function</span> (<span class="params">argument</span>) &#123;</span><br><span class="line">        <span class="comment">// 接口请求成功时调用</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;接口请求成功&#x27;</span>);</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">beforeSend</span>: <span class="keyword">function</span> (<span class="params">argument</span>) &#123;&#125;, <span class="comment">// 在发送请求之前调用,可以做一些验证之类的处理</span></span><br><span class="line">    <span class="attr">error</span>: <span class="keyword">function</span> (<span class="params">argument</span>) &#123;</span><br><span class="line">        <span class="comment">// 接口请求失败时调用</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;接口请求失败&#x27;</span>);</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;);</span><br></pre>

<p>代码举例：</p>
<p>（1）index.html</p>
<pre class="highlight"><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">title</span>&gt;</span>jquery-ajax<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;button&quot;</span> <span class="attr">value</span>=<span class="string">&quot;点击&quot;</span> <span class="attr">id</span>=<span class="string">&quot;btn&quot;</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;showInfo&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">&quot;text/javascript&quot;</span> <span class="attr">src</span>=<span class="string">&quot;jquery-1.11.2.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">&quot;text/javascript&quot;</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript">            $(<span class="keyword">function</span> (<span class="params"></span>) &#123;</span></span><br><span class="line"><span class="language-javascript">                $(<span class="string">&#x27;#btn&#x27;</span>).<span class="title function_">click</span>(<span class="keyword">function</span> (<span class="params"></span>) &#123;</span></span><br><span class="line"><span class="language-javascript">                    $.<span class="title function_">ajax</span>(&#123;</span></span><br><span class="line"><span class="language-javascript">                        <span class="attr">url</span>: <span class="string">&#x27;https://xxx.com/getUserInfo.php&#x27;</span>, <span class="comment">// 接口的请求地址</span></span></span><br><span class="line"><span class="language-javascript">                        <span class="attr">dataType</span>: <span class="string">&#x27;text&#x27;</span>,</span></span><br><span class="line"><span class="language-javascript">                        <span class="attr">data</span>: <span class="string">&#x27;name=fox&amp;age=18&#x27;</span>, <span class="comment">// 请求参数</span></span></span><br><span class="line"><span class="language-javascript">                        <span class="attr">type</span>: <span class="string">&#x27;get&#x27;</span>,</span></span><br><span class="line"><span class="language-javascript">                        <span class="attr">success</span>: <span class="keyword">function</span> (<span class="params">data</span>) &#123;</span></span><br><span class="line"><span class="language-javascript">                            <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;接口请求成功&#x27;</span>);</span></span><br><span class="line"><span class="language-javascript">                            <span class="title function_">alert</span>(data);</span></span><br><span class="line"><span class="language-javascript">                            <span class="comment">// $(&quot;#showInfo&quot;).html(data);</span></span></span><br><span class="line"><span class="language-javascript">                        &#125;,</span></span><br><span class="line"><span class="language-javascript">                        <span class="attr">error</span>: <span class="keyword">function</span> (<span class="params">err</span>) &#123;</span></span><br><span class="line"><span class="language-javascript">                            <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;接口请求失败：&#x27;</span> + err);</span></span><br><span class="line"><span class="language-javascript">                        &#125;,</span></span><br><span class="line"><span class="language-javascript">                    &#125;);</span></span><br><span class="line"><span class="language-javascript">                &#125;);</span></span><br><span class="line"><span class="language-javascript">            &#125;);</span></span><br><span class="line"><span class="language-javascript">        </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre>

<p>（2）data.php：</p>
<pre class="highlight"><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line"></span><br><span class="line"><span class="variable">$text</span> = <span class="string">&#x27;hello world&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">echo</span> <span class="variable">$text</span>;</span><br><span class="line"></span><br><span class="line"> <span class="meta">?&gt;</span></span><br><span class="line"></span><br></pre>

<h2 id="我的公众号"><a href="#我的公众号" class="headerlink" title="我的公众号"></a>我的公众号</h2><p>想学习<strong>更多技能</strong>？不妨关注我的微信公众号：<strong>千古壹号</strong>。</p>
<p>扫一扫，你将发现另一个全新的世界，而这将是一场美丽的意外：</p>
<p><img  srcset="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20300%20300'%3E%3C/svg%3E" data-src="https://img.smyhvae.com/20200102.png" class="lozad post-image"src="https://img.smyhvae.com/20200102.png"></p>
<pre class="highlight"><span class="line"></span><br></pre>

  </div>
  <div>
    
      <div 
        class="post-note note-warning copyright" 
        style="margin-top: 42px">
        <p>
          <span style="font-weight: bold;">作者：</span><a 
            target="_blank" 
            rel="nofollow noopener noreferrer" 
            href="/about">
            zwl5670
          </a>
        </p>
        <p>
          <span style="font-weight: bold;">文章链接：</span><a 
            target="_blank" 
            rel="nofollow noopener noreferrer" 
            href="https://zwl5670.gitee.io/2006/06/01/06-JavaScript%E5%9F%BA%E7%A1%80%EF%BC%9A%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B/02-Ajax%E5%85%A5%E9%97%A8%E5%92%8C%E5%8F%91%E9%80%81http%E8%AF%B7%E6%B1%82/">
            https://zwl5670.gitee.io/2006/06/01/06-JavaScript%E5%9F%BA%E7%A1%80%EF%BC%9A%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B/02-Ajax%E5%85%A5%E9%97%A8%E5%92%8C%E5%8F%91%E9%80%81http%E8%AF%B7%E6%B1%82/
          </a>
        </p>
        <p><span style="font-weight: bold;">版权声明：</span>本博客所有文章除特别声明外，均采用<a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">CC BY-NC-SA 4.0 协议</a>。转载请注明出处！</p>
      </div>
    
  </div>
</article>
<div class="nav">
  
    <div class="nav-item-prev">
      <a 
        href="/2006/06/01/06-JavaScript%E5%9F%BA%E7%A1%80%EF%BC%9A%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B/00-%E6%9C%8D%E5%8A%A1%E5%99%A8%E5%88%86%E7%B1%BB%E5%8F%8APHP%E5%85%A5%E9%97%A8/" 
        class="nav-link">
        <i class="iconfont icon-left nav-prev-icon"></i>
        <div>
          <div class="nav-label">上一篇</div>
          
            <div class="nav-title">00-服务器分类及PHP入门 </div>
          
        </div>
      </a>
    </div>
  
  
    <div class="nav-item-next">
      <a 
        href="/2006/06/01/06-JavaScript%E5%9F%BA%E7%A1%80%EF%BC%9A%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B/03-Ajax%E4%BC%A0%E8%BE%93json%E5%92%8CXML/" 
        class="nav-link">
        <div>
          <div class="nav-label">下一篇</div>
          
            <div class="nav-title">03-Ajax传输json和XML </div>
          
        </div>
        <i class="iconfont icon-right nav-next-icon"></i>
      </a>
    </div>
  
</div>

<div 
  class="card card-content toc-card" 
  id="mobiletoc">
  <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%90%8C%E6%AD%A5%E5%92%8C%E5%BC%82%E6%AD%A5%E5%9B%9E%E9%A1%BE"><span class="toc-text">同步和异步回顾</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%90%8C%E6%AD%A5%E5%92%8C%E5%BC%82%E6%AD%A5%E7%9A%84%E7%AE%80%E5%8D%95%E7%90%86%E8%A7%A3"><span class="toc-text">同步和异步的简单理解</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%82%E6%AD%A5%E6%9B%B4%E6%96%B0%E7%BD%91%E7%AB%99"><span class="toc-text">异步更新网站</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Ajax"><span class="toc-text">Ajax</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Ajax-%E7%9A%84%E6%A6%82%E5%BF%B5"><span class="toc-text">Ajax 的概念</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Ajax-%E5%8E%9F%E7%90%86%EF%BC%88%E5%8F%91%E9%80%81-Ajax-%E8%AF%B7%E6%B1%82%E7%9A%84%E4%BA%94%E4%B8%AA%E6%AD%A5%E9%AA%A4%EF%BC%89"><span class="toc-text">Ajax 原理（发送 Ajax 请求的五个步骤）</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#XMLHttpRequest-%E5%AF%B9%E8%B1%A1%E8%AF%A6%E8%A7%A3"><span class="toc-text">XMLHttpRequest 对象详解</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%91%E9%80%81%E8%AF%B7%E6%B1%82"><span class="toc-text">发送请求</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#POST-%E8%AF%B7%E6%B1%82%E6%97%B6%E6%B3%A8%E6%84%8F"><span class="toc-text">POST 请求时注意</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#onreadystatechange-%E4%BA%8B%E4%BB%B6"><span class="toc-text">onreadystatechange 事件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9C%8D%E5%8A%A1%E5%99%A8%E5%93%8D%E5%BA%94%E7%9A%84%E5%86%85%E5%AE%B9"><span class="toc-text">服务器响应的内容</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%89%8B%E5%86%99-Ajax"><span class="toc-text">手写 Ajax</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%89%8B%E5%86%99%E7%AC%AC%E4%B8%80%E4%B8%AA-Ajax-%E8%AF%B7%E6%B1%82"><span class="toc-text">手写第一个 Ajax 请求</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B0%81%E8%A3%85-Ajax-%E8%AF%B7%E6%B1%82%EF%BC%88%E9%87%8D%E8%A6%81%EF%BC%89"><span class="toc-text">封装 Ajax 请求（重要）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Ajax-%E8%AF%B7%E6%B1%82%EF%BC%9Aget-%E8%AF%B7%E6%B1%82%E4%B8%BE%E4%BE%8B"><span class="toc-text">Ajax 请求：get 请求举例</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Ajax-%E5%A4%9A%E4%B8%AA%E6%8E%A5%E5%8F%A3%E7%9A%84%E5%B5%8C%E5%A5%97%E8%AF%B7%E6%B1%82"><span class="toc-text">Ajax 多个接口的嵌套请求</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#jQuery-%E4%B8%AD%E7%9A%84-Ajax"><span class="toc-text">jQuery 中的 Ajax</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%88%91%E7%9A%84%E5%85%AC%E4%BC%97%E5%8F%B7"><span class="toc-text">我的公众号</span></a></li></ol>
</div>
            </main>
            <aside class="right-column">
              <div class="sticky-widescreen">
  
  
    <article class="card card-content toc-card">
      <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%90%8C%E6%AD%A5%E5%92%8C%E5%BC%82%E6%AD%A5%E5%9B%9E%E9%A1%BE"><span class="toc-text">同步和异步回顾</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%90%8C%E6%AD%A5%E5%92%8C%E5%BC%82%E6%AD%A5%E7%9A%84%E7%AE%80%E5%8D%95%E7%90%86%E8%A7%A3"><span class="toc-text">同步和异步的简单理解</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%82%E6%AD%A5%E6%9B%B4%E6%96%B0%E7%BD%91%E7%AB%99"><span class="toc-text">异步更新网站</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Ajax"><span class="toc-text">Ajax</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Ajax-%E7%9A%84%E6%A6%82%E5%BF%B5"><span class="toc-text">Ajax 的概念</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Ajax-%E5%8E%9F%E7%90%86%EF%BC%88%E5%8F%91%E9%80%81-Ajax-%E8%AF%B7%E6%B1%82%E7%9A%84%E4%BA%94%E4%B8%AA%E6%AD%A5%E9%AA%A4%EF%BC%89"><span class="toc-text">Ajax 原理（发送 Ajax 请求的五个步骤）</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#XMLHttpRequest-%E5%AF%B9%E8%B1%A1%E8%AF%A6%E8%A7%A3"><span class="toc-text">XMLHttpRequest 对象详解</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%91%E9%80%81%E8%AF%B7%E6%B1%82"><span class="toc-text">发送请求</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#POST-%E8%AF%B7%E6%B1%82%E6%97%B6%E6%B3%A8%E6%84%8F"><span class="toc-text">POST 请求时注意</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#onreadystatechange-%E4%BA%8B%E4%BB%B6"><span class="toc-text">onreadystatechange 事件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9C%8D%E5%8A%A1%E5%99%A8%E5%93%8D%E5%BA%94%E7%9A%84%E5%86%85%E5%AE%B9"><span class="toc-text">服务器响应的内容</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%89%8B%E5%86%99-Ajax"><span class="toc-text">手写 Ajax</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%89%8B%E5%86%99%E7%AC%AC%E4%B8%80%E4%B8%AA-Ajax-%E8%AF%B7%E6%B1%82"><span class="toc-text">手写第一个 Ajax 请求</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B0%81%E8%A3%85-Ajax-%E8%AF%B7%E6%B1%82%EF%BC%88%E9%87%8D%E8%A6%81%EF%BC%89"><span class="toc-text">封装 Ajax 请求（重要）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Ajax-%E8%AF%B7%E6%B1%82%EF%BC%9Aget-%E8%AF%B7%E6%B1%82%E4%B8%BE%E4%BE%8B"><span class="toc-text">Ajax 请求：get 请求举例</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Ajax-%E5%A4%9A%E4%B8%AA%E6%8E%A5%E5%8F%A3%E7%9A%84%E5%B5%8C%E5%A5%97%E8%AF%B7%E6%B1%82"><span class="toc-text">Ajax 多个接口的嵌套请求</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#jQuery-%E4%B8%AD%E7%9A%84-Ajax"><span class="toc-text">jQuery 中的 Ajax</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%88%91%E7%9A%84%E5%85%AC%E4%BC%97%E5%8F%B7"><span class="toc-text">我的公众号</span></a></li></ol>
    </article>
  
  
  <article class="card card-content">
    <div class="recent-posts-card">
  <div class="recent-posts-header">
    <i 
      class="iconfont icon-wenzhang_huaban" 
      style="padding-right: 2px;">
    </i>最近文章
  </div>
  <div class="recent-posts-list">
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/11-React%20Navive%E5%88%9D%E8%AF%86/"><div class="recent-posts-item-content">11-React Navive初识</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/10-AntD%E6%A1%86%E6%9E%B6%E7%9A%84upload%E7%BB%84%E4%BB%B6%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87%E6%97%B6%E4%BD%BF%E7%94%A8customRequest%E6%96%B9%E6%B3%95%E8%87%AA%E5%AE%9A%E4%B9%89%E4%B8%8A%E4%BC%A0%E8%A1%8C%E4%B8%BA/"><div class="recent-posts-item-content">10-AntD框架的upload组件上传图片时使用customRequest方法自定义上传行为</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/09-AntD%E6%A1%86%E6%9E%B6%E7%9A%84upload%E7%BB%84%E4%BB%B6%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87%E6%97%B6%E9%81%87%E5%88%B0%E7%9A%84%E4%B8%80%E4%BA%9B%E5%9D%91/"><div class="recent-posts-item-content">09-AntD框架的upload组件上传图片时遇到的一些坑</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/08-Ant%20Design%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8/"><div class="recent-posts-item-content">08-Ant Design的基本使用</div></a>
      </div>
    
  </div>
</div>
  </article>
  
  
</div>
            </aside>
          </div>
        </div>
      </div>
    </div>
     
    <footer class="footer">
  <div class="footer-container">
    <div>
      <div class="footer-dsc">
        <span>
          Copyright ©
          
            2023
          
          
        </span>
        &nbsp;
        <a 
          href="/" 
          class="footer-link">
          前端面试
        </a>
      </div>
    </div>

    
      <div class="footer-dsc">
        
          Powered by
          <a 
            href="https://hexo.io/" 
            class="footer-link" 
            target="_blank" 
            rel="nofollow noopener noreferrer">
            &nbsp;Hexo
          </a>
        
        
          <span>&nbsp;|&nbsp;</span>
        
        
          Theme -
          <a 
            href="https://github.com/theme-kaze" 
            class="footer-link" 
            target="_blank"
            rel="nofollow noopener noreferrer">
            &nbsp;Kaze
          </a>
        
      </div>
    
    
    
    
</footer>
 
    
  <a 
    role="button" 
    id="scrollbutton" 
    class="basebutton" 
    aria-label="回到顶部">
    <i class="iconfont icon-arrowleft button-icon"></i>
  </a>

<a 
  role="button" 
  id="menubutton"
  aria-label="menu button"
  class="basebutton">
  <i class="iconfont icon-menu button-icon"></i>
</a>
<a 
  role="button" 
  id="popbutton" 
  class="basebutton" 
  aria-label="控制中心">
  <i class="iconfont icon-expand button-icon"></i>
</a>
<a 
  role="button" 
  id="darkbutton" 
  class="basebutton darkwidget" 
  aria-label="夜色模式">
  <i class="iconfont icon-weather button-icon"></i>
</a>
<a 
  role="button" 
  id="searchbutton" 
  class="basebutton searchwidget" 
  aria-label="搜索">
  <i class="iconfont icon-search button-icon"></i>
</a> 
     
     
     
      <script>
  var addImgLayout = function () {
    var img = document.querySelectorAll('.post-content img')
    var i
    for (i = 0; i < img.length; i++) {
      var wrapper = document.createElement('a')
      wrapper.setAttribute('href', img[i].getAttribute('data-src'))
      wrapper.setAttribute('aria-label', 'illustration')
      wrapper.style.cssText =
        'width: 100%; display: flex; justify-content: center;'
      if (img[i].alt) wrapper.dataset.caption = img[i].alt
      wrapper.dataset.nolink = true
      img[i].before(wrapper)
      wrapper.append(img[i])
      var divWrap = document.createElement('div')
      divWrap.classList.add('gallery')
      wrapper.before(divWrap)
      divWrap.append(wrapper)
    }
    baguetteBox.run('.gallery')
  }
</script>
<script>
  loadScript(
    "/js/lib/lightbox/baguetteBox.min.js",
    addImgLayout
  )
</script>
 
     
     
    <script src="/js/main.js"></script> 
     
    
      <script>
        var addLazyload = function () {
          var observer = lozad('.lozad', {
            load: function (el) {
              el.srcset = el.getAttribute('data-src')
            },
            loaded: function (el) {
              el.classList.add('loaded')
            },
          })
          observer.observe()
        }
      </script>
      <script>
        loadScript('/js/lib/lozad.min.js', addLazyload)
      </script>
    
    <script src="//instant.page/5.1.0" type="module"
      integrity="sha384-by67kQnR+pyfy8yWP4kPO12fHKRLHZPfEsiSXR8u2IKcTdxD805MGUXBzVPnkLHw"></script>
    
    
  </body>
</html>
